import 'dart:convert';

import 'package:containerbox_study/value/api.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'encrypt_untils.dart';
import 'errorInterceptor.dart';



class HttpsUtil{
  static HttpsUtil instance = HttpsUtil._interal();
  factory HttpsUtil() => instance;

  // static HttpsUtil? instance; 
  // static HttpsUtil getInstance(){
  //   if (instance == null) {
  //     instance = HttpsUtil._interal();
  //   }
  //   return instance!;
  // }

  Dio? dio;
  HttpsUtil._interal() {
     BaseOptions options = BaseOptions(
       baseUrl: Api.SERVER_API_URL,
       //连接服务器超时时间，单位是毫秒.
       connectTimeout: 10000,
       // 响应流上前后两次接受到数据的间隔，单位为毫秒。
       receiveTimeout: 5000,
       headers: {'channel' : 'AppStore', 'versionNo' : '40'},
       contentType: 'application/json; charset=utf-8',
       responseType: ResponseType.json,
     );
     dio = Dio(options);
     //添加错误拦截器
     dio!.interceptors.add(ErrorInterceptor());
   }

   Future post(
     String path,{
     BuildContext? context,
     dynamic params,
     Options? options,
     }) async {
       Options requestOptions = options ?? Options();
       Map<String, dynamic> tokenHeader = {'cookie' : 'token=8eb2f5055ebb4459805d6c5a154675f80'};
       requestOptions = requestOptions.copyWith(headers: tokenHeader);
       Map<String, String> dataParam = {};
       if (params != null) {
          String encrypted = await EncryptUntils.encodeString(json.encode(params));
          dataParam = {'data' : encrypted};
       }
      print('path = $path');
      var response = await dio!.post(path, queryParameters: dataParam, options: requestOptions);  
      return response.data; 
     }
}

